package com.film.service.impl.account;

import com.film.jwt.JwtUtil;
import com.film.service.account.RegisterService;
import com.film.utils.MySqlConnection;
import org.springframework.stereotype.Service;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashMap;
import java.util.Map;

@Service
public class RegisterServiceImpl implements RegisterService {

    @Override
    public Map<String, String> register(String username, String password, String confirmedPassword) {
        System.out.println(username);
        System.out.println(password);
        System.out.println(confirmedPassword);
        Map<String,String> resp = new HashMap<>();
        if (username == null) {
            resp.put("error_message", "用户名不能为空");
            return resp;
        }

        if (password == null || confirmedPassword == null) {
            resp.put("error_message", "密码不能为空");
            return resp;
        }

        username = username.trim();
        if (username.length() == 0) {
            resp.put("error_message", "用户名不能为空");
            return resp;
        }

        if (password.length() == 0 || confirmedPassword.length() == 0) {
            resp.put("error_message", "密码不能为空");
            return resp;
        }

        if (username.length() > 100) {
            resp.put("error_message", "用户名长度不能大于100");
            return resp;
        }

        if (password.length() > 100 || confirmedPassword.length() > 100) {
            resp.put("error_message", "密码长度不能大于100");
            return resp;
        }

        if (!password.equals(confirmedPassword)) {
            resp.put("error_message", "两次输入的密码不相同");
            return resp;
        }

        try {
            Statement stmt = MySqlConnection.connect.createStatement();
            String sql = "select * from User where username = " + "'" + username + "'";
            System.out.println(sql);
            ResultSet resultSet = stmt.executeQuery(sql);
            if (resultSet.next()) {
                resp.put("error_message", "该用户名已存在");
                return resp;
            }
            resultSet.close();



            //生成token
            Map<String, Object> jwtMap = JwtUtil.generateToken(username, JwtUtil.SECRET);
            String token = (String)(jwtMap.get("token"));
            resp.put("token", token);

            //插入新用户
            String insertSql = "insert into User(username, password, token) value('" + username + "'," + "'" + password + "'," + "'" + token + "')";
            System.out.println(insertSql);
            stmt.execute(insertSql);
            resp.put("error_message", "success");



            System.out.println("注册成功!!!");
            return resp;


        } catch (SQLException e) {
            e.printStackTrace();
        }

        resp.put("error_message", "未知错误");

        return resp;


    }
}
